import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

import operator from './modules/operator';
import enums from './modules/enums';
import { removeNullUndefined } from "@/utils/index.js";

import {
  stats
} from "@/api/system";
Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  modules[moduleName].namespaced = true; //打开命名空间
  return modules
}, {})

const store = new Vuex.Store({
  modules,
  getters,
  operator,
  enums,
  state: {
    mapWarn: {
      onlineCount: 0,
      offlineCount: 0,
      alarmCount: 0,
      totalCount: 0
    },
  },
  mutations: {
    SET_MAP_WARN: (state, count) => {
      state.mapWarn = count;
    },
  },
  actions: {
    generateMapWarn({
      commit
    }, param) {
      return new Promise((resolve, reject) => {
        if (param.map) {
          commit('SET_MAP_WARN', param.map);
          resolve(param.map)
        } else {
          stats(`/equip/dist`, 'get', {...removeNullUndefined({
            regionCode: param.code
          })}, 2).then(res => {
            const {
              data
            } = res;
            commit('SET_MAP_WARN', data);
            resolve(data)
          }).catch(error => {
            reject(error)
          })
        }
      })
    },
  }
})
export default store
